class PrioritQueue{
  constructor() {
    this.array = []
    this.size = 0
  }
  enQueue(value) {
    this.array[this.size++] = value
    this.upAdjust()
  }
  deQueue() {
    if(this.size < 0) {
      throw new Error("the queue is empty !")
    }
    let head = this.array[0]
    this.array[0]  = this.array[--this.size]
    this.downAdjust()
    return head
  }
  upAdjust() {
    let childIndex = this.size - 1
    let parentIndex = Math.floor((childIndex-1)/2) 
    let temp = this.array[childIndex]
    while(childIndex > 0 && temp > this.array[parentIndex]) {
      this.array[childIndex] = this.array[parentIndex]
      childIndex = parentIndex
      parentIndex = Math.floor((parentIndex-1) / 2) 
    }
    this.array[childIndex] = temp
  }
  downAdjust() {
    let parentIndex = 0
    let temp = this.array[parentIndex]
    let childIndex = 1
    while(childIndex < this.size) {
      if(childIndex + 1 < this.size && this.array[childIndex + 1] < this.array[childIndex]) {
        childIndex++
      }
      if(temp >= this.array[childIndex]) {
        break
      }
      this.array[parentIndex] = this.array[childIndex]
      parentIndex = childIndex
      childIndex = childIndex*2 + 1
    }
    this.array[parentIndex] = temp
  }
}


let priorityQueue = new PrioritQueue()
priorityQueue.enQueue(3)
priorityQueue.enQueue(5)
priorityQueue.enQueue(10)
priorityQueue.enQueue(2)
priorityQueue.enQueue(7)

console.log('出队元素：' + priorityQueue.deQueue())